package com.taotao.rest.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.mapper.TbContentMapper;
import com.taotao.po.TbContent;
import com.taotao.po.TbContentExample;
import com.taotao.po.TbContentExample.Criteria;
import com.taotao.pojo.TaotaoResult;
import com.taotao.rest.component.impl.JedisSingleImpl;
import com.taotao.rest.service.ContentService;
import com.taotao.util.JsonUtils;

@Service
public class ContentServiceImpl implements ContentService {

	@Autowired
	private TbContentMapper contentMapper;
	
	@Resource
	private JedisSingleImpl jedisClient;
	
	@Value("${REDIS_CONTENT_KEY}")
	private String REDIS_CONTENT_KEY;
	
	@Override
	public List<TbContent> getContentList(Long cid) {
		
		// 查询缓存是是否存在
		String json = jedisClient.hget(REDIS_CONTENT_KEY, String.valueOf(cid));
		if (!StringUtils.isBlank(json)) {
			List<TbContent> list = JsonUtils.jsonToList(json, TbContent.class);
			return list;
		}	
		// 根据cid查询内容列表
		TbContentExample example = new TbContentExample();
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(cid);
		//执行查询
		List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example);
		if (list!=null) {
			if (!list.isEmpty()) {
				// 存入redis缓存中
				String value = JsonUtils.objectToJson(list);
				jedisClient.hset(REDIS_CONTENT_KEY, String.valueOf(cid), value);
			}
		}	
		return list;
	}

	@Override
	public TaotaoResult synchronizedContent(Long cid) {
		jedisClient.hdel(REDIS_CONTENT_KEY,String.valueOf(cid));
		return TaotaoResult.ok();
	}
}
